package walletsyslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/uniqueid"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type DepositDirectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDepositDirectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DepositDirectLogic {
	return &DepositDirectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 直接充值
func (l *DepositDirectLogic) DepositDirect(in *pb.DepositDirectReq) (*pb.DepositDirectResp, error) {
	defer utils.RecoverPanic()

	dMoneyAmount, err := decimal.NewFromString(in.MoneyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	iMoneyAmount := dMoneyAmount.Mul(decimal.NewFromInt(100)).IntPart()
	//
	dCurrencyAmount := decimal.Zero
	if in.CurrencyAmount != "" {
		dCurrencyAmount, err = decimal.NewFromString(in.CurrencyAmount)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
		}
	}
	iCurrencyAmount := dCurrencyAmount.Mul(decimal.NewFromInt(100)).IntPart()
	// 充值流水
	df := wallet.UserDepositFlow{
		FlowNo:         uniqueid.GenFlowNoX(),
		Uid:            in.Uid,
		MoneyType:      in.MoneyType,
		MoneyAmount:    iMoneyAmount,
		CurrencyType:   in.CurrencyType,
		CurrencyAmount: iCurrencyAmount,
		State:          walletkey.DepositFlowStateSuccess,
		ExternalFlowNo: in.ExFlow,
		PayChannelId:   in.PayChannelId,
		PayAccount:     "",
		PayAccountType: 0,
	}
	// 查询用户钱包
	uw, err := l.svcCtx.UserWalletModel.FindOneByUidMoneyType(l.ctx, in.Uid, in.MoneyType)
	if err != nil && err != wallet.ErrNotFound {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	// 计算钱包余额
	var dInAmount decimal.Decimal
	dInAmount = decimal.NewFromInt(df.MoneyAmount)
	var rsp pb.DepositDirectResp
	rsp.MoneyType = in.MoneyType

	err = l.svcCtx.UserWalletModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		// 创建支付流水
		_, err2 := l.svcCtx.UserDepositFlowModel.InsertTrans(ctx, tx, &df)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		// 更新钱包
		if uw == nil || uw.Id <= 0 { // 未创建钱包
			uw = &wallet.UserWallet{
				Uid:       df.Uid,
				MoneyType: df.MoneyType,
				Amount:    df.MoneyAmount,
				State:     dbkey.Enable,
			}
			_, err2 = l.svcCtx.UserWalletModel.InsertTrans(ctx, tx, uw)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			rsp.Balance = dInAmount.String()
		} else { // 已创建钱包
			// 更新钱包余额
			err2 = l.svcCtx.UserWalletModel.AddAmountTrans(ctx, tx, df.MoneyAmount, uw.Id, uw.Uid, uw.MoneyType)
			if err2 != nil {
				l.Logger.Errorf("err == ", zap.Error(err2))
				return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
			}
			var dUwAmount decimal.Decimal
			dUwAmount = decimal.NewFromInt(uw.Amount)
			rsp.Balance = dUwAmount.Add(dInAmount).Div(decimal.NewFromInt(100)).StringFixedBank(2)
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	// 发送通知
	//l.after(in.Uid, walletkey.GetMoneyNameByMoneyType(in.MoneyType), in.MoneyAmount)
	return &rsp, nil
}

//
//func (l *DepositDirectLogic) after(uid int64, moneyName, moneyAmount string) {
//	kqMsg := kqmsg.KqAddUserNotifyMsg{
//		Uid:     uid,
//		Title:   userkey.UserNotifyMsgTitleDepositSuccess01EnIn,
//		MsgType: userkey.UserNotifyMsgTypeDepositSuccess01,
//	}
//
//	msgContent := userkey.UserNotifyMsgContent1{
//		Text:     fmt.Sprintf(userkey.UserNotifyMsgContentDepositSuccess01EnIn, moneyAmount, moneyName),
//		Url:      "",
//		PagePath: "",
//	}
//	var cBuf []byte
//	cBuf, err := json.Marshal(msgContent)
//	if err != nil {
//		l.Logger.Errorf("DepositDirectLogic after json.Marshal(msgContent) err:%v", err)
//		return
//	}
//	kqMsg.MsgContent = string(cBuf)
//
//	var kqMsgBuf []byte
//	kqMsgBuf, err = json.Marshal(kqMsg)
//	if err != nil {
//		l.Logger.Errorf("DepositDirectLogic after json.Marshal(kqMsg) err:%v", err)
//		return
//	}
//
//	err = l.svcCtx.KqAddUserNotifyMsgClient.Push(string(kqMsgBuf))
//	if err != nil {
//		l.Logger.Errorf("DepositDirectLogic after Push err:%v", err)
//		return
//	}
//	return
//}
